import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:permission_handler/permission_handler.dart';


class SharePromotionController extends GetxController {
  // 用于标识 RepaintBoundary 的全局 key
  final GlobalKey captureKey = GlobalKey();
  RxString inviteCode = 'AS234561F'.obs;

  // 检查并申请相册权限
  Future<bool> checkAndRequestPermission() async {
    // 检查权限状态（Android：WRITE_EXTERNAL_STORAGE；iOS：PHOTO_LIBRARY_ADD_ONLY）
    PermissionStatus status;
    if (Platform.isAndroid) {
      status = await Permission.storage.request();
    } else if (Platform.isIOS) {
      status = await Permission.photosAddOnly.request();
    } else {
      return false; // 其他平台暂不支持
    }
    return status.isGranted;
  }

  Future<void> captureAndSaveToGallery(BuildContext context) async {
    // 1. 检查权限
    bool hasPermission = await checkAndRequestPermission();
    if (!hasPermission) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('需要相册权限才能保存图片')),
      );
      return;
    }

    try {
      // 2. 获取组件渲染对象
      RenderRepaintBoundary boundary = captureKey.currentContext!
          .findRenderObject() as RenderRepaintBoundary;

      // 3. 转换为图片
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);

      // 4. 转换为 PNG 字节
      ByteData? byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      // 5. 使用 plus 版本保存到相册（API 与原版本基本一致）
      final result = await ImageGallerySaverPlus.saveImage(
        pngBytes,
        quality: 100,
        name: 'screenshot_${DateTime.now().millisecondsSinceEpoch}',
      );

      // 6. 处理结果
      if (result['isSuccess'] == true) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('图片已保存到相册')),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('保存失败：')),
        );
      }
    } catch (e) {
      print('截图失败：$e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('截图过程出错')),
      );
    }
  }
}
